package com.shinaier.laundry.snlstore.setting.ui.fragment;

import android.app.DownloadManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.common.network.FProtocol;
import com.common.utils.PreferencesUtils;
import com.common.utils.ToastUtil;
import com.common.utils.VersionInfoUtils;
import com.shinaier.laundry.snlstore.R;
import com.shinaier.laundry.snlstore.base.fragment.BaseFragment;
import com.shinaier.laundry.snlstore.main.UserCenter;
import com.shinaier.laundry.snlstore.main.ui.LoginActivity;
import com.shinaier.laundry.snlstore.network.Constants;
import com.shinaier.laundry.snlstore.network.entity.Entity;
import com.shinaier.laundry.snlstore.network.entity.SettingsEntity;
import com.shinaier.laundry.snlstore.network.entity.UpdataEntity;
import com.shinaier.laundry.snlstore.network.parser.Parsers;
import com.shinaier.laundry.snlstore.setting.ui.activity.ConnectBluetoothActivity;
import com.shinaier.laundry.snlstore.setting.ui.activity.CooperativeFactoryActivity;
import com.shinaier.laundry.snlstore.setting.ui.activity.FeedbackActivity;
import com.shinaier.laundry.snlstore.setting.ui.activity.RevisePasswordActivity;
import com.shinaier.laundry.snlstore.setting.ui.activity.StoreDetailActivity;
import com.shinaier.laundry.snlstore.setting.view.UpdateDialog;
import com.shinaier.laundry.snlstore.util.ExitManager;
import com.shinaier.laundry.snlstore.view.CommonDialog;

import java.util.IdentityHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static android.content.Context.DOWNLOAD_SERVICE;

/**
 * 设置页面
 * Created by 张家洛 on 2017/2/7.
 */

public class SettingsManageFragment extends BaseFragment implements View.OnClickListener {
    private static final int REQUEST_CODE_SETTINGS = 0x1;
    private static final int REQUEST_CODE_UPDATE_VERSION = 0x2;
    private static final int REQUEST_CODE_QUIT_LOGIN = 0x3;
    public static final String DOWNLOAD_ID = "download_id";
    //"content://downloads/my_downloads"必须这样写不可更改
    public static final Uri CONTENT_URI = Uri.parse("content://downloads/my_downloads");

    private View view;
    private Context context;
    private TextView storeName;
    private TextView storePhoneNumber;
    private TextView storeCardNum;
    private TextView areaManageName;
    private TextView customerServicePhoneNum;
    private ImageView ivStoreImg;
//    private SettingsEntity settingsEntity;
    private RelativeLayout rlCustomerService;
    private RelativeLayout rlUpdateVersion;
    private String updateUrl;
    private UpdateDialog updateDialog;
    private CommonDialog dialog;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    dialog.setContent("下载中");
                    dialog.show();
                    ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
                    cachedThreadPool.execute(new DownLoadTask());
                    break;
            }
        }
    };
    private String versionNum;
    private String versionContent;
    private String versionSize;
    private long lastDownloadId = 0;
    private DownloadChangeObserver downloadObserver;
    private MaterialDialog materialDialog;
    private SettingsEntity.SettingsResult result;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        TextView textView = new TextView(getActivity());
        textView.setText("设置");
        view = inflater.inflate(R.layout.settings_frag, null);
        context = getActivity();
        loadData();
        initView();
        return view;
    }

    private void loadData() {
        IdentityHashMap<String,String> params = new IdentityHashMap<>();
        params.put("token", UserCenter.getToken(context));
        requestHttpData(Constants.Urls.URL_POST_SETTINGS,REQUEST_CODE_SETTINGS, FProtocol.HttpMethod.POST,params);
    }

    private void initView() {
        dialog = new CommonDialog(context);
        ivStoreImg = (ImageView) view.findViewById(R.id.iv_store_img);
        storeName = (TextView) view.findViewById(R.id.store_name);
        storePhoneNumber = (TextView) view.findViewById(R.id.store_phone_number);
        storeCardNum = (TextView) view.findViewById(R.id.store_card_num);
        areaManageName = (TextView) view.findViewById(R.id.area_manage_name);
        customerServicePhoneNum = (TextView) view.findViewById(R.id.customer_service_phone_num);
        RelativeLayout rlFeedback = (RelativeLayout) view.findViewById(R.id.rl_feedback);
        RelativeLayout rlRevisePhone = (RelativeLayout) view.findViewById(R.id.rl_revise_phone);
        rlCustomerService = (RelativeLayout) view.findViewById(R.id.rl_customer_service);
        TextView quitLoginBt = (TextView) view.findViewById(R.id.quit_login_bt);
        rlUpdateVersion = (RelativeLayout) view.findViewById(R.id.rl_update_version);
        RelativeLayout rlStoreInfo = (RelativeLayout) view.findViewById(R.id.rl_store_info);
        RelativeLayout rlConnectBluetooth = (RelativeLayout) view.findViewById(R.id.rl_connect_bluetooth);
        RelativeLayout rlCooperativeFactory = (RelativeLayout) view.findViewById(R.id.rl_cooperative_factory);


        rlFeedback.setOnClickListener(this);
        rlRevisePhone.setOnClickListener(this);
        quitLoginBt.setOnClickListener(this);
        rlUpdateVersion.setOnClickListener(this);
        rlStoreInfo.setOnClickListener(this);
        rlConnectBluetooth.setOnClickListener(this);
        rlCooperativeFactory.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.rl_feedback:
                //意见反馈
                startActivity(new Intent(context,FeedbackActivity.class));
                break;
            case R.id.rl_revise_phone:
                //修改密码
                startActivity(new Intent(context,RevisePasswordActivity.class));
                break;
            case R.id.rl_customer_service:
                tell(result.getService());
                break;
            case R.id.quit_login_bt:

                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setTitle("提示");
                builder.setMessage("是否确认退出登录？");
                builder.setNegativeButton("取消", null);
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int ich) {
                        //退出登录 清除registrationID 防止退出登录之后还有消息推送
                        IdentityHashMap<String,String> params = new IdentityHashMap<String, String>();
                        params.put("token",UserCenter.getToken(context));
                        requestHttpData(Constants.Urls.URL_POST_QUIT_LOGIN,REQUEST_CODE_QUIT_LOGIN, FProtocol.HttpMethod.POST,params);

                    }
                });
                AlertDialog alertDialog = builder.create();
                alertDialog.show();
                break;
            case R.id.rl_update_version:
                int versionCode = VersionInfoUtils.getVersionCode(context);
                IdentityHashMap<String,String> params = new IdentityHashMap<>();
                params.put("version_code", versionCode + "");
                params.put("token",UserCenter.getToken(context));
                requestHttpData(Constants.Urls.URL_POST_UPDATE_VERSION,REQUEST_CODE_UPDATE_VERSION,
                        FProtocol.HttpMethod.POST,params);
                break;
            case R.id.rl_store_info:
                //门店信息
                startActivity(new Intent(context,StoreDetailActivity.class));
                break;
            case R.id.rl_connect_bluetooth:
                //连接蓝牙设备
                startActivity(new Intent(context,ConnectBluetoothActivity.class));
                break;
            case R.id.rl_cooperative_factory:
                //合作工厂
                startActivity(new Intent(context,CooperativeFactoryActivity.class));
                break;
        }
    }

    @Override
    public void success(int requestCode, String data) {
        super.success(requestCode, data);
        switch (requestCode){
            case REQUEST_CODE_SETTINGS:
                if(data != null){
                    SettingsEntity settingsEntity = Parsers.getSettingsEntity(data);
                    if (settingsEntity != null){
                        if (settingsEntity.getCode() == 0){
                            result = settingsEntity.getResult();
                            setInfo();

                        }else {
                            ToastUtil.shortShow(context,settingsEntity.getMsg());
                        }
                    }

                }
                break;
            case REQUEST_CODE_UPDATE_VERSION:
                if(data != null){
                    UpdataEntity updataEntity = Parsers.getUpdataEntity(data);
                    if(updataEntity != null){
                        if(updataEntity.getRetcode() == 1){
                            versionContent = updataEntity.getDatas().getVersionContent();
                            versionNum = updataEntity.getDatas().getVersionNum();
                            versionSize = updataEntity.getDatas().getVersionSize();
                            updateDialog = new UpdateDialog(context, R.style.timerDialog,handler);
                            updateDialog.setView(versionContent, versionNum, versionSize);
                            updateDialog.show();
                            updateUrl = updataEntity.getDatas().getUrl();
                        }else {
                            ToastUtil.shortShow(context,"当前已是最新版本");
                        }
                    }
                }
                break;
            case REQUEST_CODE_QUIT_LOGIN:
                if (data != null){
                    Entity entity = Parsers.getEntity(data);
                    if (entity != null){
                        if (entity.getCode() == 0){
                            UserCenter.cleanLoginInfo(context);
                            startActivity(new Intent(context,LoginActivity.class));
                            ExitManager.instance.exit();
                        }else {
                            ToastUtil.shortShow(context,"退出登录失败，请重新再试");
                        }
                    }
                }
                break;
        }
    }

    private void setInfo() {
        ivStoreImg.setImageURI( Uri.parse(result.getmLogo()));
        storeName.setText(result.getmName());
        storePhoneNumber.setText(result.getMobileNumber());
        storeCardNum.setText(result.getBankCard());
        areaManageName.setText(result.getManager());
        customerServicePhoneNum.setText(result.getService());
        rlCustomerService.setOnClickListener(this);
    }

    public class DownLoadTask implements Runnable {

        @Override
        public void run() {
            initDownLoad();
        }
    }

    private void initDownLoad() {
        //1.得到下载对象
        DownloadManager dowanloadmanager = (DownloadManager) context.getSystemService(DOWNLOAD_SERVICE);
        //2.创建下载请求对象，并且把下载的地址放进去
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(updateUrl));
        //3.给下载的文件指定路径
        request.setDestinationInExternalFilesDir(context, Environment.DIRECTORY_DOWNLOADS, "snl_store.apk");
        //4.设置显示在文件下载Notification（通知栏）中显示的文字。6.0的手机Description不显示
        request.setTitle("速洗达" + versionNum);
        request.setDescription(versionContent);
        //5更改服务器返回的minetype为android包类型
        request.setMimeType("application/vnd.android.package-archive");
        //6.设置在什么连接状态下执行下载操作
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);
        //7. 设置为可被媒体扫描器找到
        request.allowScanningByMediaScanner();
        //8. 设置为可见和可管理
        request.setVisibleInDownloadsUi(true);
        lastDownloadId = dowanloadmanager.enqueue(request);
        //9.保存id到缓存
        PreferencesUtils.putLong(context, DOWNLOAD_ID, lastDownloadId);
        //10.采用内容观察者模式实现进度
        downloadObserver = new DownloadChangeObserver(null);
        context.getContentResolver().registerContentObserver(CONTENT_URI, true, downloadObserver);
    }

    //用于显示下载进度
    class DownloadChangeObserver extends ContentObserver {

        public DownloadChangeObserver(Handler handler) {
            super(handler);
        }

        @Override
        public void onChange(boolean selfChange) {
            DownloadManager.Query query = new DownloadManager.Query();
            query.setFilterById(lastDownloadId);
            DownloadManager dManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
            final Cursor cursor = dManager.query(query);
            if (cursor != null && cursor.moveToFirst()) {
                final int totalColumn = cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES);
                final int currentColumn = cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR);
                int totalSize = cursor.getInt(totalColumn);
                int currentSize = cursor.getInt(currentColumn);
                float percent = (float) currentSize / (float) totalSize;
                int progress = Math.round(percent * 100);
                materialDialog.setProgress(progress);
                if (progress == 100) {
                    materialDialog.dismiss();
                }
            }
        }


    }
}
